package com.suyang.syt.listener;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.suyang.syt.context.BeanFactoryContext;
import com.suyang.syt.model.User;
import com.suyang.syt.service.interfaces.LoginService;
import com.suyang.syt.service.interfaces.WeixinUserService;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.weixin.WeixinKit;

/** 微信授权拦截器 */
public class WeixinAuthorizeInterceptor extends HandlerInterceptorAdapter {
	private List<String> excludeUrls;

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		String url = request.getServletPath();
		if (session.getAttribute("loginUser") != null || excludeUrls.contains(url)) {
			return true;
		}
		String agent = request.getHeader("User-Agent");
		if (EmptyUtil.isNotEmpty(agent) && agent.indexOf("MicroMessenger") >= 0) {
			String code = request.getParameter("code");
			String state = request.getParameter("state");
			if (EmptyUtil.isNotEmpty(code) && EmptyUtil.isNotEmpty(state) && "syt2015".equals(state)) {
				String openid = WeixinKit.authorize(code);
				if (EmptyUtil.isNotEmpty(openid)) {
					WeixinUserService weixinUserService = (WeixinUserService) BeanFactoryContext.getWebApplicationContext().getBean(WeixinUserService.class);
					LoginService loginService = (LoginService) BeanFactoryContext.getWebApplicationContext().getBean(LoginService.class);
					User user = weixinUserService.updateAuthorize(openid);
					// loginService.longinHandle(user, session);
					return true;
				}
			} else {
				StringBuffer requestUrl = request.getRequestURL();
				String requestQuery = request.getQueryString();
				if (EmptyUtil.isNotEmpty(requestQuery)) {
					requestUrl = requestUrl.append("?").append(requestQuery);
				}
				response.sendRedirect(WeixinKit.replaceAuthorizeURI(requestUrl.toString()));
				return false;
			}
		}
		return true;
	}

}